/**
 * Created by shenchangmin on 16/10/10.
 */
const mysql = require('mysql');
const $conf = require('../conf/db');
const $sql = require('./articlesSql');
const $util = require('../util/util');

//使用连接池，提升性能
const pool = mysql.createPool($util.extend({}, $conf.mysql));

//向前台返回JSON
const jsonWrite = function (res, ret) {
    if (typeof ret === 'undefined') {
        res.json({
            code: '400',
            msg: '操作失败'
        });
    } else {
        res.json(ret);
    }
};

const articles = {
    add: function (req, res, next) {
        pool.getConnection(function (err, connection) {
            if (err) {
                throw err;
            }
            const param = req.query || req.params;
            connection.query($sql.insert, [param.title, param.content], function (err, result) {
                if (result) {
                    result = {
                        code: 200,
                        msg: '增加成功'
                    }
                }
                //返回json
                jsonWrite(res, result);
                //释放链接
                connection.release();
            })
        });
    },
    delete: function (req, res, next) {
        pool.getConnection(function (err, connection) {
            if (err) {
                throw err;
            }
            const param = req.query || req.params;
            connection.query($sql.delete, [param.id], function (err, result) {
                if (result.affectedRows > 0) {
                    result = {
                        code: 200,
                        msg: '删除成功'
                    }
                } else {
                    result = void 0;
                }
                //返回json
                jsonWrite(res, result);
                //释放链接
                connection.release();
            });
        });
    },
    queryById: function (req, res, next) {

    },
    queryAll: function (req, res, next) {

    },
    update: function (req, res, next) {

    }
};
module.exports = articles;